package com.sofly.service.impl.group1;

import java.util.Date;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sofly.dao.group1.IUserDao;
import com.sofly.entity.User;
import com.sofly.service.group1.IUserService;

@Service
public class UserService implements IUserService {
	@Autowired
	private IUserDao userDao;

	@Override
	public User getUser(long userId) {
		return userDao.selectByPrimaryKey(userId);
	}

	@Override
	public int addUser(User user) {
		String hashAlgorithmName = "MD5";
		Object credentials = user.getPassword();
		Object salt = ByteSource.Util.bytes(user.getName());
		int hashIterations = 1024;

		Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
		user.setPassword(result.toString());
		return userDao.insert(user);
	}

	@RequiresRoles({ "admin" })
	public void testMethod() {
		System.out.println("testMethod, time: " + new Date());

		Session session = SecurityUtils.getSubject().getSession();
		Object val = session.getAttribute("key");

		System.out.println("Service SessionVal: " + val);
	}

	@Override
	public List<User> getAllUser() {
		return userDao.getAlluser();
	}

	@Override
	public List<String> getNameList() {
		return userDao.getNameList();
	}

	@Override
	public int deleteUser(int userId) {
		Long id = (long) userId;
		return userDao.deleteUser(id);
	}

}
